<template>
  <div>
    <el-dialog
      ref="batchDialog"
      title="发起安全承诺书"
      :visible="popVisible"
      :close-on-click-modal="false"
      @close="onCancel"
    >
      <el-form ref="contractForm" label-width="120px" label-position="left" :model="contractForm" :rules="formRules">
        <el-form-item :required="true" label="选择模板" prop="TemplateId">
          <el-select placeholder="请选择模板" name="TemplateId" v-model="contractForm.TemplateId">
            <el-option
              v-for="item in templateList"
              :key="item.TemplateId"
              :label="item.TemplateName"
              :value="item.TemplateId"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item :required="true" label="签署截止时间" prop="DeadLine">
          <el-date-picker
            v-model="contractForm.DeadLine"
            type="datetime"
            placeholder="选择日期时间"
            :picker-options="pickerOptions"
          >
          </el-date-picker>
        </el-form-item>
      </el-form>
      <p>将对以下{{ list.length }}人发起劳动合同：</p>

      <el-table :data="list" element-loading-text="加载中" border fit highlight-current-row>
        <el-table-column label="姓名" min-width="120" :show-overflow-tooltip="true" align="center">
          <template slot-scope="scope">
            {{ scope.row.name }}
          </template>
        </el-table-column>
        <el-table-column label="手机号" min-width="120" :show-overflow-tooltip="true" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.mobile }}</span>
          </template>
        </el-table-column>
        <el-table-column label="身份证号" min-width="120" :show-overflow-tooltip="true" align="center">
          <template slot-scope="scope">
            {{ scope.row.idcardNo }}
          </template>
        </el-table-column>
      </el-table>
      <div class="form-footer" slot="footer">
        <el-button type="primary" class="btn" @click="onSubmit" :loading="submitLoading">确定</el-button>
        <el-button type="secondary" class="btn" @click.native.prevent="onCancel">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { mapGetters } from 'vuex';
import { getTemplateList } from '@common/api/template';
import { createSingleContract } from '@common/api/contract';
import { formatTime } from '@common/utils/time';
import { checkIDCard } from '@common/utils/validate';

export default {
  props: {
    visible: {
      type: Boolean,
      default() {
        return false;
      },
    },
    list: {
      type: Array,
      default() {
        return [];
      },
    },
  },

  data() {
    return {
      loading: true,
      templateList: [],
      contractForm: {
        TemplateId: '',
        DeadLine: '',
      },
      formRules: {
        TemplateId: [{ required: true, message: '请选择模版' }],
        DeadLine: [{ required: true, message: '请选择签署截止时间' }],
      },
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now();
        },
      },
      submitLoading: false,
    };
  },
  computed: {
    ...mapGetters(['orgname']),
    popVisible() {
      return this.visible;
    },
    hasTemplate() {
      return !this.loading && !this.templateList?.length;
    },
  },
  watch: {
    popVisible() {
      if (this.popVisible) {
        this.fetchTpls();
      }
    },
  },

  methods: {
    async fetchTpls() {
      const res = await getTemplateList({
        withPreviewUrl: false, // 是否获取模板预览链接
        // tenantTemplateType: 3, // 劳务合同
      });
      if (res?.data?.Templates?.length) {
        this.templateList = res.data.Templates;
        this.loading = false;
      } else {
        this.templateList = [];
        this.loading = false;
      }
    },
    async onSubmit() {
      this.$refs.contractForm.validate(async valid => {
        if (valid) {
          this.submitLoading = true;
          const flowInfos = this.handleFlowInfos();
          const params = {
            FlowInfos: flowInfos,
            NeedPreview: false,
            signType: 'singleC',
          };
          try {
            const response = await createSingleContract(params);
            if (response?.code === 20000) {
              this.$message({
                message: '合同创建成功',
                type: 'success',
              });
              this.$emit('batchProposalSuccess', response.data);
              this.$refs.contractForm.resetFields();
            } else {
              this.$message({
                message: '合同创建失败',
                type: 'warning',
              });
              this.$emit('batchProposalHide');
              this.$refs.contractForm.resetFields();
            }
            this.submitLoading = false;
          } catch (error) {
            this.submitLoading = false;
          }
        }
      });
    },
    onCancel() {
      this.$emit('batchProposalHide');
      this.$refs.contractForm.resetFields();
    },
    // 合同签署方信息处理
    handleFlowInfos() {
      const curTemplate = this.templateList.find(v => v.TemplateId === this.contractForm.TemplateId);
      const flowInfos = [];
      let flowApprovers = [];
      const personArr = curTemplate?.Recipients?.filter(f => f.RecipientType === 'INDIVIDUAL');
      this.list.forEach(item => {
        const usersApprover = {
          ApproverType: 'PERSON',
          RecipientId: personArr[0]?.RecipientId,
          Name: item.name,
          Mobile: item.mobile,
          WorkerId: item.id,
        };
        const callback = error => {
          if (!error) {
            usersApprover.IdCardType = 'ID_CARD';
            usersApprover.IdCardNumber = item.idcardNo;
          }
        };
        if (item.idcardNo) {
          // 身份证号有效
          checkIDCard('', item.idcardNo, callback);
        }
        flowApprovers = [usersApprover];
        flowInfos.push({
          FlowName: `${item.name}的安全承诺书(${formatTime(new Date(), { format: 'YYYY-MM-DD HH:mm' })})`,
          Deadline: +new Date(formatTime(this.contractForm.DeadLine)) / 1000,
          TemplateId: curTemplate?.TemplateId,
          FlowApprovers: flowApprovers,
        });
      });
      return flowInfos;
    },
  },
};
</script>
